/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.refunite.mobile.s60;

import apibridge.APIBridge;
import apibridge.NewFileService;
import apibridge.entities.BridgeException;
import apibridge.entities.BridgeResult;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.client.j2me.LCDUIImageLuminanceSource;
import com.google.zxing.common.GlobalHistogramBinarizer;
import org.refunite.mobile.s60.persistence.PersistenceStoreProvider;
import org.refunite.mobile.s60.ui.CollectScreen;
import org.refunite.mobile.s60.ui.SendDataScreen;
import org.refunite.mobile.s60.ui.SettingsScreen;
import org.refunite.mobile.s60.util.FormController;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.WaitScreen;
import org.netbeans.microedition.util.SimpleCancellableTask;

/**
 * @author I040022
 */
public class RefugeesUnited extends MIDlet implements CommandListener {

    private boolean midletPaused = false;

    private SettingsScreen settingsScreen;
    private SendDataScreen sendDataScreen;
    private CollectScreen collectScreen;
    private FormController formControllerInstance;


    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Command exitCommand;
    private WaitScreen waitScreen;
    private Form StartScreen;
    private Gauge gauge;
    private List list;
    private Image imageCollectData;
    private Image imageSendData;
    private Image imageSettings;
    private Image imageSplash;
    private SimpleCancellableTask task;
    //</editor-fold>//GEN-END:|fields|0|

    /**
     * The HelloMIDlet constructor.
     */
    public RefugeesUnited() {
        settingsScreen = new SettingsScreen(this);
        sendDataScreen = new SendDataScreen(this);
        collectScreen = new CollectScreen(this);
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getWaitScreen());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here

    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|













    //</editor-fold>
    //</editor-fold>












        // write pre-action user code here

        // write post-action user code here




    //<editor-fold defaultstate="collapsed" desc=" Generated Method: backToMenu ">//GEN-BEGIN:|95-entry|0|96-preAction
    /**
     * Performs an action assigned to the backToMenu entry-point.
     */
    public void backToMenu() {//GEN-END:|95-entry|0|96-preAction
        // write pre-action user code here
        switchDisplayable(null, getList());//GEN-LINE:|95-entry|1|96-postAction
        // write post-action user code here
    }//GEN-BEGIN:|95-entry|2|
    //</editor-fold>//GEN-END:|95-entry|2|













    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == list) {//GEN-BEGIN:|7-commandAction|1|119-preAction
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|1|119-preAction
                // write pre-action user code here
                listAction();//GEN-LINE:|7-commandAction|2|119-postAction
                // write post-action user code here
            } else if (command == exitCommand) {//GEN-LINE:|7-commandAction|3|138-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|4|138-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|5|162-preAction
        } else if (displayable == waitScreen) {
            if (command == WaitScreen.FAILURE_COMMAND) {//GEN-END:|7-commandAction|5|162-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|6|162-postAction
                // write post-action user code here
            } else if (command == WaitScreen.SUCCESS_COMMAND) {//GEN-LINE:|7-commandAction|7|161-preAction
                // write pre-action user code here
                switchDisplayable(null, getList());//GEN-LINE:|7-commandAction|8|161-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|9|7-postCommandAction
        }//GEN-END:|7-commandAction|9|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|10|
    //</editor-fold>//GEN-END:|7-commandAction|10|


    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: list ">//GEN-BEGIN:|117-getter|0|117-preInit
    /**
     * Returns an initiliazed instance of list component.
     * @return the initialized component instance
     */
    public List getList() {
        if (list == null) {//GEN-END:|117-getter|0|117-preInit
            // write pre-init user code here
            list = new List("Refugees United", Choice.IMPLICIT);//GEN-BEGIN:|117-getter|1|117-postInit
            list.append("Collect Data", getImageCollectData());
            list.append("Send Data", getImageSendData());
            list.append("Settings", getImageSettings());
            list.addCommand(getExitCommand());
            list.setCommandListener(this);
            list.setFitPolicy(Choice.TEXT_WRAP_OFF);
            list.setSelectedFlags(new boolean[] { false, false, false });//GEN-END:|117-getter|1|117-postInit
            // write post-init user code here
        }//GEN-BEGIN:|117-getter|2|
        return list;
    }
    //</editor-fold>//GEN-END:|117-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: listAction ">//GEN-BEGIN:|117-action|0|117-preAction
    /**
     * Performs an action assigned to the selected list element in the list component.
     */
    public void listAction() {//GEN-END:|117-action|0|117-preAction
        // enter pre-action user code here
        String __selectedString = getList().getString(getList().getSelectedIndex());//GEN-BEGIN:|117-action|1|121-preAction
        if (__selectedString != null) {
            if (__selectedString.equals("Collect Data")) {//GEN-END:|117-action|1|121-preAction
                // write pre-action user code here
                this.formControllerInstance.initForm();
                if(PersistenceStoreProvider.getFormLanguage() == null){
                    String[] languages = this.formControllerInstance.getAvailableLanguages();
                    if(languages.length == 1){
                        PersistenceStoreProvider.saveFormLanguage(languages[0]);
                        this.formControllerInstance.setUsedLanguage(PersistenceStoreProvider.getFormLanguage());
                        this.collectScreen.display();
                    }else{
                        this.settingsScreen.languageSelectorScreen(false);
                        switchDisplayable(null, this.settingsScreen.getSelectLanguage());
                    }
                }else{
                    try{
                        this.formControllerInstance.setUsedLanguage(PersistenceStoreProvider.getFormLanguage());
                        this.collectScreen.display();
                    }catch(Exception e){
                        String[] languages = this.formControllerInstance.getAvailableLanguages();
                        if(languages.length == 1){
                            PersistenceStoreProvider.saveFormLanguage(languages[0]);
                            this.formControllerInstance.setUsedLanguage(PersistenceStoreProvider.getFormLanguage());
                            this.collectScreen.display();
                        }else{
                            this.settingsScreen.languageSelectorScreen(false);
                            switchDisplayable(null, this.settingsScreen.getSelectLanguage());
                        }
                    }
                }
//GEN-LINE:|117-action|2|121-postAction
                // write post-action user code here
            } else if (__selectedString.equals("Send Data")) {//GEN-LINE:|117-action|3|123-preAction
                // write pre-action user code here
                this.sendDataScreen.display();//GEN-LINE:|117-action|4|123-postAction
                // write post-action user code here
            } else if (__selectedString.equals("Settings")) {//GEN-LINE:|117-action|5|129-preAction
                // write pre-action user code here
                this.settingsScreen.display();//GEN-LINE:|117-action|6|129-postAction
                // write post-action user code here
            }//GEN-BEGIN:|117-action|7|117-postAction
        }//GEN-END:|117-action|7|117-postAction
        // enter post-action user code here
    }//GEN-BEGIN:|117-action|8|
    //</editor-fold>//GEN-END:|117-action|8|



    //</editor-fold>
    //</editor-fold>





    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|137-getter|0|137-preInit
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|137-getter|0|137-preInit
            // write pre-init user code here
            exitCommand = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|137-getter|1|137-postInit
            // write post-init user code here
        }//GEN-BEGIN:|137-getter|2|
        return exitCommand;
    }
    //</editor-fold>//GEN-END:|137-getter|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageSplash ">//GEN-BEGIN:|144-getter|0|144-preInit
    /**
     * Returns an initiliazed instance of imageSplash component.
     * @return the initialized component instance
     */
    public Image getImageSplash() {
        if (imageSplash == null) {//GEN-END:|144-getter|0|144-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|144-getter|1|144-@java.io.IOException
                imageSplash = Image.createImage("/images/tmpphpOmipzV.png");
            } catch (java.io.IOException e) {//GEN-END:|144-getter|1|144-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|144-getter|2|144-postInit
            // write post-init user code here
        }//GEN-BEGIN:|144-getter|3|
        return imageSplash;
    }
    //</editor-fold>//GEN-END:|144-getter|3|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: StartScreen ">//GEN-BEGIN:|149-getter|0|149-preInit
    /**
     * Returns an initiliazed instance of StartScreen component.
     * @return the initialized component instance
     */
    public Form getStartScreen() {
        if (StartScreen == null) {//GEN-END:|149-getter|0|149-preInit
            // write pre-init user code here
            StartScreen = new Form("", new Item[] { getGauge() });//GEN-LINE:|149-getter|1|149-postInit
            // write post-init user code here
        }//GEN-BEGIN:|149-getter|2|
        return StartScreen;
    }
    //</editor-fold>//GEN-END:|149-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: gauge ">//GEN-BEGIN:|151-getter|0|151-preInit
    /**
     * Returns an initiliazed instance of gauge component.
     * @return the initialized component instance
     */
    public Gauge getGauge() {
        if (gauge == null) {//GEN-END:|151-getter|0|151-preInit
            // write pre-init user code here
            gauge = new Gauge("", false, 400, 0);//GEN-BEGIN:|151-getter|1|151-postInit
            gauge.setLayout(ImageItem.LAYOUT_CENTER | Item.LAYOUT_TOP | Item.LAYOUT_BOTTOM | Item.LAYOUT_VCENTER | ImageItem.LAYOUT_NEWLINE_BEFORE | Item.LAYOUT_EXPAND | Item.LAYOUT_2);//GEN-END:|151-getter|1|151-postInit
            // write post-init user code here
        }//GEN-BEGIN:|151-getter|2|
        return gauge;
    }
    //</editor-fold>//GEN-END:|151-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageCollectData ">//GEN-BEGIN:|153-getter|0|153-preInit
    /**
     * Returns an initiliazed instance of imageCollectData component.
     * @return the initialized component instance
     */
    public Image getImageCollectData() {
        if (imageCollectData == null) {//GEN-END:|153-getter|0|153-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|153-getter|1|153-@java.io.IOException
                imageCollectData = Image.createImage("/collectData.png");
            } catch (java.io.IOException e) {//GEN-END:|153-getter|1|153-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|153-getter|2|153-postInit
            // write post-init user code here
        }//GEN-BEGIN:|153-getter|3|
        return imageCollectData;
    }
    //</editor-fold>//GEN-END:|153-getter|3|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageSendData ">//GEN-BEGIN:|154-getter|0|154-preInit
    /**
     * Returns an initiliazed instance of imageSendData component.
     * @return the initialized component instance
     */
    public Image getImageSendData() {
        if (imageSendData == null) {//GEN-END:|154-getter|0|154-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|154-getter|1|154-@java.io.IOException
                imageSendData = Image.createImage("/sendData.png");
            } catch (java.io.IOException e) {//GEN-END:|154-getter|1|154-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|154-getter|2|154-postInit
            // write post-init user code here
        }//GEN-BEGIN:|154-getter|3|
        return imageSendData;
    }
    //</editor-fold>//GEN-END:|154-getter|3|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageSettings ">//GEN-BEGIN:|155-getter|0|155-preInit
    /**
     * Returns an initiliazed instance of imageSettings component.
     * @return the initialized component instance
     */
    public Image getImageSettings() {
        if (imageSettings == null) {//GEN-END:|155-getter|0|155-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|155-getter|1|155-@java.io.IOException
                imageSettings = Image.createImage("/settings.png");
            } catch (java.io.IOException e) {//GEN-END:|155-getter|1|155-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|155-getter|2|155-postInit
            // write post-init user code here
        }//GEN-BEGIN:|155-getter|3|
        return imageSettings;
    }
    //</editor-fold>//GEN-END:|155-getter|3|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: waitScreen ">//GEN-BEGIN:|158-getter|0|158-preInit
    /**
     * Returns an initiliazed instance of waitScreen component.
     * @return the initialized component instance
     */
    public WaitScreen getWaitScreen() {
        if (waitScreen == null) {//GEN-END:|158-getter|0|158-preInit
            // write pre-init user code here
            waitScreen = new WaitScreen(getDisplay());//GEN-BEGIN:|158-getter|1|158-postInit
            waitScreen.setTitle("Refugees United");
            waitScreen.setCommandListener(this);
            waitScreen.setFullScreenMode(true);
            waitScreen.setImage(getImageSplash());
            waitScreen.setText("Loading...");
            waitScreen.setTask(getTask());//GEN-END:|158-getter|1|158-postInit
            // write post-init user code here
        }//GEN-BEGIN:|158-getter|2|
        return waitScreen;
    }
    //</editor-fold>//GEN-END:|158-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: task ">//GEN-BEGIN:|163-getter|0|163-preInit
    /**
     * Returns an initiliazed instance of task component.
     * @return the initialized component instance
     */
    public SimpleCancellableTask getTask() {
        if (task == null) {//GEN-END:|163-getter|0|163-preInit
            // write pre-init user code here
            task = new SimpleCancellableTask();//GEN-BEGIN:|163-getter|1|163-execute
            task.setExecutable(new org.netbeans.microedition.util.Executable() {
                public void execute() throws Exception {//GEN-END:|163-getter|1|163-execute
                    // write task-execution user code here
                    long startTime = System.currentTimeMillis();
                    formControllerInstance = FormController.getInstance();

                }//GEN-BEGIN:|163-getter|2|163-postInit
            });//GEN-END:|163-getter|2|163-postInit
            // write post-init user code here
        }//GEN-BEGIN:|163-getter|3|
        return task;
    }
    //</editor-fold>//GEN-END:|163-getter|3|



















    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;

        

    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }


    private void getContentOfBarcode(InputStream is){
        try{
            Image image = Image.createImage(is);
            // save to images
/*
            String filePath =  System.getProperty("fileconn.dir.photos");


            String filename = filePath + "Test" + System.currentTimeMillis() + ".png";
            FileConnection fileConnection = (FileConnection) Connector.open(filename,Connector.READ_WRITE);
            fileConnection.create();
            OutputStream stream = fileConnection.openOutputStream();
            stream.write(raw);
            stream.flush();
            stream.close();
            fileConnection.close();
*/
            LuminanceSource source = new LCDUIImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
            //BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Reader reader = new MultiFormatReader();
            Result result = reader.decode(bitmap);

            Form res = new Form("Finished");
            StringItem a = new StringItem("",result.getText());
            res.append(a);
            getDisplay().setCurrent(res);
        }catch(Exception e ){
            Form res = new Form("ERROR");
            StringItem a = new StringItem("",e.getMessage());
            res.append(a);
            getDisplay().setCurrent(res);
            
        }

    }

    public String replaceSlash(String input){
        char backslash = new String("\\").charAt(0);
        char slash = new String("/").charAt(0);
        if(input.indexOf("\\") != -1){
            input = input.replace(backslash, slash);
            replaceSlash(input);
        }
        return input;
    }

    private class CustomTimerTask  extends TimerTask {

        public CustomTimerTask() {
        }

        /**
         * As the timer fires, this method is invoked. Set gauge
         * based on goUp
         */
        public void run() {
            int currentValue = gauge.getValue();
            if(gauge.getValue() < gauge.getMaxValue()){
                gauge.setValue(currentValue + 10);
            }else{
                this.cancel();
                switchDisplayable(null, getList());
            }
        }
    }

    public FormController getFormController(){
        return this.formControllerInstance;
    }

    public void backFromLanguageSettings(){
        this.collectScreen.display();
    }
    public void showCameraCanvas(){
        APIBridge bridge = APIBridge.getInstance();
        bridge.Initialize(this);
        final NewFileService service = (NewFileService) bridge.createService("service.newfileservice");
        Thread thread = new Thread() {
 
            public void run() {
                String message = "";
                try {
                    Hashtable filter = new Hashtable();
                    filter.put("NewFileType", "Image");
                    message += "Start";
                    BridgeResult res = service.TakePhoto(filter);
                    Hashtable returnValue = (Hashtable) res.getReturnValue();
                    message += "|Picture taken|";
                    String pathToFile = returnValue.get("src").toString();


                    String fileName = replaceSlash(pathToFile);
                   message += "|"+fileName +"|";
                    FileConnection fileConnection = (FileConnection) Connector.open("file:///"+fileName, Connector.READ);
                    message += "fileconnectionDone";
                    getContentOfBarcode(fileConnection.openInputStream());
                    fileConnection.close();

                } catch (BridgeException ex) {
                    Form res = new Form("ERRORBRIDGE");
                    StringItem a = new StringItem("",ex.getMessage());
                    res.append(a);
                    getDisplay().setCurrent(res);
                } catch (Exception ex) {
                    Form res = new Form("ERROR");
                    StringItem a = new StringItem("",message);
                    res.append(a);
                    getDisplay().setCurrent(res);
                }
            }
        };
        thread.start();
    }
}
